package com.useeinfo.oa.open.api.inspection;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.tools.AliJsonObjectCover;
import com.useeinfo.framework.sugar.tools.DateTimeUtils;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.PlanMessageSendBiz;
import com.useeinfo.oa.modules.base.biz.PositionBiz;
import com.useeinfo.oa.modules.base.biz.ResourceBiz;
import com.useeinfo.oa.modules.base.entity.*;
import com.useeinfo.oa.modules.base.enums.ResourceTypeEnum;
import com.useeinfo.oa.modules.inspection.biz.*;
import com.useeinfo.oa.modules.inspection.entity.*;
import com.useeinfo.oa.modules.inspection.enums.InputTypeEnum;
import com.useeinfo.oa.modules.inspection.enums.InsOrderOperationEnum;
import com.useeinfo.oa.modules.inspection.enums.InsOrderStatusEnum;
import com.useeinfo.oa.modules.security.biz.OrganizationBiz;
import com.useeinfo.oa.modules.security.biz.SystemUserBiz;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("/api/mobile/facilityInspectionSnap")
public class FacilityInspectionSnapAPI {
    @Autowired
    private SystemUserBiz systemUserBiz;
    @Autowired
    private ResourceBiz resourceBiz;
    @Autowired
    private OrganizationBiz organizationBiz;
    @Autowired
    private PositionBiz positionBiz;
    @Autowired
    private InspectionOrderBiz inspectionOrderBiz;
    @Autowired
    private InspectionOrderLogBiz inspectionOrderLogBiz;
    @Autowired
    private InspectionOrderWorkContentBiz inspectionOrderWorkContentBiz;
    @Autowired
    private FacilityInspectionSnapBiz facilityInspectionSnapBiz;
    @Autowired
    private InspectionWorkingHoursBiz inspectionWorkingHoursBiz;
    @Autowired
    private InspectionPartnerBiz inspectionPartnerBiz;
    @Autowired
    private PlanMessageSendBiz planMessageSendBiz;


    /**
     * 设备维保内容的临时保存(单个设备)
     */
    @RequestMapping(value = "/singleSnapTemporarySave")
    public ResultDto singleSnapTemporarySave(@RequestParam(value = "temporaryData", required = false) String temporaryData,
                                             @RequestParam(value = "facilityInspectionSnapId", required = false) String facilityInspectionSnapId,
                                             HttpServletRequest request) {
        JSONObject results = new JSONObject();
        if (StringUtils.isBlank(facilityInspectionSnapId) || StringUtils.isBlank(temporaryData)) {
            return ResultUtil.error("参数异常");
        }
        FacilityInspectionSnap facilityInspectionSnap = facilityInspectionSnapBiz.findModel(StringConverters.ToLong(facilityInspectionSnapId));
        if (facilityInspectionSnap == null) {
            return ResultUtil.error("参数异常");
        }
        InspectionOrder inspectionOrder = facilityInspectionSnap.getInspectionOrder();
        if (inspectionOrder == null) {
            return ResultUtil.error("参数异常");
        }
        JSONArray jsonArray = JSONArray.parseArray(temporaryData);
        JSONArray resultArray = new JSONArray();
        JSONArray applicationArray = new JSONArray();
        Long applicationId = null;//默认应用场景ID
        if (jsonArray.size() > 0) {
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject resultObject = new JSONObject();
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String inspectionOrderWorkContentId = jsonObject.getString("inspectionOrderWorkContentId");//维保内容ID
                String result = jsonObject.getString("result");//输入内容
                JSONArray photoArray = jsonObject.getJSONArray("photoPath");
                String abnormal = jsonObject.getString("abnormal");//照片路径
                applicationId = StringConverters.ToLong(jsonObject.getString("applicationId"));//当前的应用场景ID
                InspectionOrderWorkContent inspectionOrderWorkContent = inspectionOrderWorkContentBiz.findModel(StringConverters.ToLong(inspectionOrderWorkContentId));
                if (inspectionOrderWorkContent == null) {
                    continue;
                }
                inspectionOrderWorkContent.setResult(result);
                inspectionOrderWorkContent.setContentPhoto(null);
                if (StringUtils.isNotBlank(abnormal)) {
                    inspectionOrderWorkContent.setAbnormal(Boolean.parseBoolean(abnormal));
                }
                if (photoArray != null && photoArray.size() > 0) {
                    Set<Resource> resourceSet = new HashSet<>();
                    for (int j = 0; j < photoArray.size(); j++) {
                        String path = StringConverters.null2String(photoArray.getString(j));
                        if (StringUtils.isNotBlank(path)) {
                            Resource resource = new Resource();
                            resource.setResourceTypeEnum(ResourceTypeEnum.IMG);
                            resource.setPath(path);
                            resource.setResourceName("巡检照片");
                            resourceBiz.addOrUpdate(resource);
                            resourceSet.add(resource);
                        }
                    }
                    inspectionOrderWorkContent.setContentPhoto(resourceSet);
                }
                if (StringUtils.isNotBlank(result) || photoArray != null) {
                    inspectionOrderWorkContent.setFinishTime(new Date());
                }
                inspectionOrderWorkContentBiz.addOrUpdate(inspectionOrderWorkContent);
                //2019-01-21 Sheaodn增加返回值
                resultObject.put("inputTypeEnum", StringConverters.null2String(inspectionOrderWorkContent.getInputTypeEnum().getCode()));
                if (InputTypeEnum.COMPLETE_TYPE.getCode().equals(inspectionOrderWorkContent.getInputTypeEnum().getCode()) || InputTypeEnum.STATUS_TYPE.getCode().equals(inspectionOrderWorkContent.getInputTypeEnum().getCode())) {
                    String[] names = inspectionOrderWorkContent.getInputTypeEnum().getName().split("、");
                    JSONArray nameArray = new JSONArray();
                    nameArray.addAll(Arrays.asList(names));
                    resultObject.put("inputType", nameArray);
                } else {
                    resultObject.put("inputType", StringConverters.null2String(inspectionOrderWorkContent.getInputTypeEnum().getName()));
                }
                resultObject.put("contentId", StringConverters.null2Long(inspectionOrderWorkContent.getId()));
                resultObject.put("unit", StringConverters.null2String(inspectionOrderWorkContent.getUnit()));
                resultObject.put("applicationId", StringConverters.null2Long(inspectionOrderWorkContent.getApplication_scenarios_id()));
                resultObject.put("applicationName", StringConverters.null2String(inspectionOrderWorkContent.getApplication_scenarios_name()));
                resultObject.put("photo", StringConverters.null2Boolean(inspectionOrderWorkContent.getPhoto()));
                resultObject.put("maxNumber", StringConverters.null2Double(inspectionOrderWorkContent.getMaxNumber()));
                resultObject.put("minNumber", StringConverters.null2Double(inspectionOrderWorkContent.getMinNumber()));
                resultObject.put("abnormal", StringConverters.null2Boolean(inspectionOrderWorkContent.getAbnormal()));
                resultObject.put("name", StringConverters.null2String(inspectionOrderWorkContent.getName()));
                resultObject.put("content", StringConverters.null2String(inspectionOrderWorkContent.getContent()));
                JSONArray array = new JSONArray();
                if(StringUtils.isNotBlank(inspectionOrderWorkContent.getContent())){
                    array = JSONArray.parseArray(inspectionOrderWorkContent.getContent());
                }
                resultObject.put("contentArray", array);
                resultObject.put("category", StringConverters.null2String(inspectionOrderWorkContent.getCategory()));
                resultObject.put("result", StringConverters.null2String(inspectionOrderWorkContent.getResult()));
                resultObject.put("photos", photoArray);
                String pdfPath = "";
                if (StringUtils.isNotBlank(inspectionOrderWorkContent.getResourceIds())) {
                    Resource resource = resourceBiz.findModel(StringConverters.ToLong(inspectionOrderWorkContent.getResourceIds()));
                    if (resource != null) {
                        pdfPath = resource.getPath();
                    }
                }
                resultObject.put("resources", pdfPath);
                resultArray.add(resultObject);
            }
        }
        //更新该设备的默认应用场景ID
        if(applicationId!=null){
            facilityInspectionSnap.setApplicationScenariosId(applicationId);
            facilityInspectionSnapBiz.addOrUpdate(facilityInspectionSnap);
        }
        //更新百分比(以及工单是否异常 以及更新inspectionOrder表工时字段)
        inspectionOrderBiz.updatePercent(inspectionOrder.getId() + "");
        facilityInspectionSnap = facilityInspectionSnapBiz.findModel(StringConverters.ToLong(facilityInspectionSnapId));
        //操作日志
        inspectionOrderLogBiz.saveInspectionOrderLog(inspectionOrder, InsOrderOperationEnum.TEMP_SUBMIT_ORDER, request);
        results.put("contents", resultArray);
        //查询applicationArray
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("facilityInspectionSnapId", facilityInspectionSnapId);
        List<InspectionOrderWorkContent> inspectionOrderWorkContentList = inspectionOrderWorkContentBiz.findList(queryParam);
        if (CollectionUtils.isNotEmpty(inspectionOrderWorkContentList)) {
            for (InspectionOrderWorkContent inspectionOrderWorkContent : inspectionOrderWorkContentList) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("applicationId", inspectionOrderWorkContent.getApplication_scenarios_id());
                jsonObject.put("applicationName", inspectionOrderWorkContent.getApplication_scenarios_name());
                if (!applicationArray.contains(jsonObject)) {
                    applicationArray.add(jsonObject);
                }
                results.put("applicationArray", applicationArray);
                results.put("facilityCode", facilityInspectionSnap.getFacilityCode());
                results.put("facilityId", facilityInspectionSnap.getId());
                results.put("applicationId", facilityInspectionSnap.getApplicationScenariosId()==null?"":facilityInspectionSnap.getApplicationScenariosId());
                results.put("facilityName", facilityInspectionSnap.getFacilityName());
                results.put("inspectionName", facilityInspectionSnap.getInspectionName());
                results.put("spec", facilityInspectionSnap.getSpec());
                results.put("completed", facilityInspectionSnap.isCompleted());
                results.put("snapId", facilityInspectionSnap.getId()); }
            }
        return ResultUtil.success(results);
    }

    /**
     * 设备维保内容的临时保存(多个)
     */
    @RequestMapping(value = "/temporarySave")
    public ResultDto temporarySave(@RequestParam(value = "temporaryData", required = false) String temporaryData,
                                   @RequestParam(value = "inspectionOrderId", required = false) String inspectionOrderId,
                                   @RequestParam(value = "userId", required = false) String userId,
                                   @RequestParam(value = "workingHours", required = false) String workingHoursString,
                                   HttpServletRequest request) {
        if (StringUtils.isBlank(inspectionOrderId) || StringUtils.isBlank(temporaryData)) {
            return ResultUtil.error("参数异常");
        }
        InspectionOrder inspectionOrder = inspectionOrderBiz.findModel(StringConverters.ToLong(inspectionOrderId));
        if (inspectionOrder == null) {
            return ResultUtil.error("参数异常");
        }
        JSONArray jsonArray = JSONArray.parseArray(temporaryData);
        List<String> facilityInspectionSnapIds = new ArrayList<>();
        if (jsonArray.size() > 0) {
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String facilityInspectionSnapId = jsonObject.getString("facilityInspectionSnapId");//维保设备ID
                String inspectionOrderWorkContentId = jsonObject.getString("inspectionOrderWorkContentId");//维保内容ID
                String result = jsonObject.getString("result");//输入内容
                JSONArray photoArray = jsonObject.getJSONArray("photoPath");
                String abnormal = jsonObject.getString("abnormal");//照片路径
                //保存该设备下的当前应用场景
                Long applicationId = StringConverters.ToLong(jsonObject.getString("applicationId"));//当前的应用场景ID
                FacilityInspectionSnap facilityInspectionSnap = facilityInspectionSnapBiz.findModel(StringConverters.ToLong(facilityInspectionSnapId));
                if(facilityInspectionSnap!=null){
                    facilityInspectionSnap.setApplicationScenariosId(applicationId);
                    facilityInspectionSnapBiz.addOrUpdate(facilityInspectionSnap);
                }

                if (!facilityInspectionSnapIds.contains(facilityInspectionSnapId)) {
                    facilityInspectionSnapIds.add(facilityInspectionSnapId);
                }
                InspectionOrderWorkContent inspectionOrderWorkContent = inspectionOrderWorkContentBiz.findModel(StringConverters.ToLong(inspectionOrderWorkContentId));
                if (inspectionOrderWorkContent == null) {
                    continue;
                }
                inspectionOrderWorkContent.setResult(result);
                inspectionOrderWorkContent.setContentPhoto(null);
                if (StringUtils.isNotBlank(abnormal)) {
                    inspectionOrderWorkContent.setAbnormal(Boolean.parseBoolean(abnormal));
                }
                if (photoArray != null && photoArray.size() > 0) {
                    Set<Resource> resourceSet = new HashSet<>();
                    for (int j = 0; j < photoArray.size(); j++) {
                        String path = StringConverters.null2String(photoArray.getString(j));
                        if (StringUtils.isNotBlank(path)) {
                            Resource resource = new Resource();
                            resource.setResourceTypeEnum(ResourceTypeEnum.IMG);
                            resource.setPath(path);
                            resource.setResourceName("巡检内容照片");
                            resourceBiz.addOrUpdate(resource);
                            resourceSet.add(resource);
                        }
                    }
                    inspectionOrderWorkContent.setContentPhoto(resourceSet);
                }
                if (StringUtils.isNotBlank(result) || photoArray != null) {
                    inspectionOrderWorkContent.setFinishTime(new Date());
                }
                inspectionOrderWorkContentBiz.addOrUpdate(inspectionOrderWorkContent);
            }
        }
        //更新百分比(以及工单是否异常 以及更新inspectionOrder表工时字段)
        inspectionOrderBiz.updatePercent(inspectionOrderId);
        //操作日志
        inspectionOrderLogBiz.saveInspectionOrderLog(inspectionOrder, InsOrderOperationEnum.TEMP_SUBMIT_ORDER, request);
        //返回最新的内容
        ResultDto resultDto = inspectionOrderBiz.detail(inspectionOrderId);
        JSONObject obj = (JSONObject) resultDto.getData();
        JSONObject result = new JSONObject();
        JSONArray unfinished = new JSONArray();
        unfinished = obj.getJSONArray("unfinished");
        JSONArray finished = new JSONArray();
        finished = obj.getJSONArray("finished");
        result.put("unfinished", unfinished);
        result.put("finished", finished);
        return ResultUtil.success(result);
    }


    /**
     * 提交工单
     */
    @RequestMapping(value = "/submitOrder")
    public ResultDto submitOrder(@RequestParam(value = "inspectionOrderId", required = false) String inspectionOrderId,
                                 @RequestParam(value = "participantInputs", required = false) String participantInputs,
                                 HttpServletRequest request) {
        InspectionOrder inspectionOrder = inspectionOrderBiz.findModel(StringConverters.ToLong(inspectionOrderId));
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        SystemUser systemUser=SessionKeyUtils.getSessionUser(request);
        if (inspectionOrder == null) {
            return ResultUtil.error("参数异常");
        }
        if (inspectionOrder.getCancel() || inspectionOrder.getDelay() || inspectionOrder.isAuditing()) {
            return ResultUtil.error("该工单正在审核中，无法提交");
        }
        //查询所有snap 如果都是完成状态 则可以提交工单
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("inspectionOrderId", inspectionOrderId);
        List<FacilityInspectionSnap> facilityInspectionSnapList = facilityInspectionSnapBiz.findList(queryParam);
        boolean status = true;
        for (FacilityInspectionSnap facilityInspectionSnap : facilityInspectionSnapList) {
            if (!facilityInspectionSnap.isCompleted()) {
                status = false;
                break;
            }
        }
        if (!status) {
            return ResultUtil.error("工单未完成，无法提交");
        }
        String content="";
        List<Long> ids = new ArrayList<>();
        if (inspectionOrder.getAuditCompleteID() != null) {
            JSONArray jsonArray = JSONArray.parseArray(inspectionOrder.getCompleteFlow());
            if (jsonArray != null && jsonArray.size() > 0) {
                inspectionOrder.setOrderStatusEnum(InsOrderStatusEnum.IN_AUDITING);
                inspectionOrder.setLevel(1);
                if (jsonArray.size() == 1) {
                    inspectionOrder.setAuditLast(true);
                } else {
                    inspectionOrder.setAuditFirst(true);
                }
                inspectionOrder.setAuditing(true);
                JSONObject jsonObject = jsonArray.getJSONObject(0);
                Long organizationId = jsonObject.getLong("organizationId");
                Organization organization = organizationBiz.findModel(organizationId);
                inspectionOrder.setOrganization(organization);
                String nodeTypeEnum = jsonObject.getString("nodeTypeEnum");
                Long relationId = jsonObject.getLong("relationId");
                if (nodeTypeEnum.equals("USER")) {
                    SystemUser user = systemUserBiz.findModel(relationId);
                    inspectionOrder.setAuditSystemUser(user);
                      ids.add(user.getId());
                } else {
                    Position position = positionBiz.findModel(relationId);
                    inspectionOrder.setPosition(position);
                    ids.addAll(systemUserBiz.getUserIdsByPosition(relationId.toString(),organizationId.toString(),enterprise.getId()+""));
                }


            } else {
                inspectionOrder.setOrderStatusEnum(InsOrderStatusEnum.COMPLETED);
            }
             content = "巡检单:" + inspectionOrder.getOrderCode() + "已完成!";


        } else {
            inspectionOrder.setOrderStatusEnum(InsOrderStatusEnum.COMPLETED);
             content = "巡检单:" + inspectionOrder.getOrderCode() + "已完成,等待审核!";
        }
        inspectionOrder.setPercent(100);
        inspectionOrder.setFinishTime(new Date());
        inspectionOrder.setCompleteUser(systemUser);
        inspectionOrder.setComplete(true);
        long thisHours=DateTimeUtils.newGetDiffMinutesTime(DateTimeUtils.parse("yyyy-MM-dd HH:mm:ss", DateTimeUtils.format(inspectionOrder.getPresenceTime(), "yyyy-MM-dd HH:mm:ss")), new Date());
        inspectionOrder.setWorkingHours(inspectionOrder.getWorkingHours()+thisHours);
        //参与人工时计算
        JSONArray participantInputsArray = JSON.parseArray(participantInputs);
        long totalWorkingHours=0;
        if (participantInputsArray.size() > 0) {
            for (int i = 0; i < participantInputsArray.size(); i++) {
                JSONObject j = participantInputsArray.getJSONObject(i);
                Long partnerId = AliJsonObjectCover.ObjectLong(j, "userId");
                Long workingHours = AliJsonObjectCover.ObjectLong(j, "workingHours");
                QueryParam q = new QueryParam();
                q.getSqlMap().put("partnerId", partnerId == null ? "-1" : partnerId + "");
                q.getSqlMap().put("inspectionOrderId", inspectionOrder.getId() + "");
                q.getSqlMap().put("enterpriseId", StringConverters.null2String(enterprise.getId()));
                List<InspectionPartner> inspectionPartnerList = inspectionPartnerBiz.findList(q);
                if (CollectionUtils.isEmpty(inspectionPartnerList)) {
                    return ResultUtil.error("参与人不存在！");
                }
                InspectionPartner inspectionPartner = inspectionPartnerList.get(0);
                totalWorkingHours+=workingHours;
                inspectionPartner.setWorkingHours(inspectionPartner.getWorkingHours() + workingHours);
                inspectionPartnerBiz.addOrUpdate(inspectionPartner);
            }
        }
        inspectionOrder.setTotalWorkingHours(inspectionOrder.getTotalWorkingHours()+thisHours+totalWorkingHours);
        inspectionOrderBiz.addOrUpdate(inspectionOrder);

        //更新百分比(以及工单是否异常 以及更新inspectionOrder表工时字段)
        inspectionOrderBiz.updatePercent(inspectionOrderId);

        //操作日志
        inspectionOrderLogBiz.saveInspectionOrderLog(inspectionOrder, InsOrderOperationEnum.SUBMIT_ORDER, request);
        //消息推送
        if(!ids.contains(inspectionOrder.getReceiveUser().getId())){
            ids.add(inspectionOrder.getReceiveUser().getId());//工单人也需要消息推送
        }
        planMessageSendBiz.senMsg(inspectionOrder.getId(),"inspection",inspectionOrder.getEnterprise(),ids,content);
        return ResultUtil.success();
    }
}
